import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Tag,
  Space,
  Typography,
  Row,
  Col,
  message,
  Avatar,
  Descriptions,
  Divider,
} from 'antd';
import {
  PlusOutlined,
  TeamOutlined,
  UserOutlined,
  PhoneOutlined,
  MailOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SearchOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { getDictionaryByTypeApi } from '../../api/dictionaryApi';
import { getMemberApi, addMemberApi, updateMemberApi } from '../../api/memberApi';
import AddMembers from './addMembers';

const { Title, Text } = Typography;
const { Option } = Select;

const Members = () => {
  // 一、状态定义
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingMember, setEditingMember] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [filterRole, setFilterRole] = useState('all');
  const [memberRoles, setMemberRoles] = useState([]); // 成员角色下拉列表
  const [tableData, setTableData] = useState([]); // table展示数据
  const [loading, setLoading] = useState(false); // table加载状态
  // 添加分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 二、生命周期管理
  useEffect(() => {
    // 加载查询条件
    // 加载成员角色下拉列表
    fetchMemberRoles();
    fetchMembers();
  }, []);

  // 三、函数定义
  // 获取成员角色下拉列表（只获取启用状态的）
  const fetchMemberRoles = async () => {
    try {
      const res = await getDictionaryByTypeApi({ dictType: 'member_type', status: '0' });
      if (res.code === '0' || res.code === 200) {
        const roles = res.data.map(item => ({
          value: item.dictValue,
          label: item.dictLabel
        }));
        setMemberRoles(roles);
      } else {
        message.error('获取成员角色下拉列表失败');
      }
    } catch (error) {
      message.error('获取成员角色下拉列表失败');
    }
  };

  // 查询按钮点击事件
  const handleSearch = async () => {
    // 构建查询参数
    const searchParams = {};

    // 按姓名搜索
    if (searchText.trim()) {
      searchParams.memberName = searchText.trim();
    }

    // 按角色过滤
    if (filterRole !== 'all') {
      searchParams.memberType = filterRole;
    }

    // 重置分页到第一页
    setPagination(prev => ({
      ...prev,
      current: 1,
    }));

    // 等待状态更新后再查询
    setTimeout(async () => {
      await fetchMembers(searchParams);
      message.success('查询完成');
    }, 0);
  };

  // 查询成员数据
  const fetchMembers = async (searchParams = {}) => {
    setLoading(true);
    try {
      // 合并搜索参数和分页参数
      const params = {
        ...searchParams,
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
      };

      const response = await getMemberApi(params);
      if (response && response.code === '0') {
        setTableData(response.data.list || response.data);
        // 更新总数
        setPagination(prev => ({
          ...prev,
          total: response.data.total || response.data.length,
        }));
      } else {
        message.error('获取成员数据失败');
      }
    } catch (error) {
      message.error('获取成员数据出错，使用默认数据');
    } finally {
      setLoading(false);
    }
  };

  // 重置按钮点击事件
  const handleReset = async () => {
    setSearchText('');
    setFilterRole('all');
    // 重置分页到第一页
    setPagination(prev => ({
      ...prev,
      current: 1,
    }));
    // 等待状态更新后再查询
    setTimeout(async () => {
      await fetchMembers();
      message.info('已重置搜索条件');
    }, 0);
  };

  // 分页变化处理
  const handleTableChange = (paginationInfo) => {
    setPagination(prev => ({
      ...prev,
      current: paginationInfo.current,
      pageSize: paginationInfo.pageSize,
    }));

    // 构建当前搜索参数
    const searchParams = {};
    if (searchText.trim()) {
      searchParams.memberName = searchText.trim();
    }
    if (filterRole !== 'all') {
      searchParams.memberType = filterRole;
    }

    // 使用新的分页参数重新查询
    fetchMembers(searchParams);
  };

  // table展示列
  const columns = [
    {
      title: '成员',
      dataIndex: 'memberName',
      key: 'memberName',
      width: 150,
      align: 'center',
      render: (text, record) => (
        <Space>
          <Avatar src={record.avatar} icon={<UserOutlined />} />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '角色',
      dataIndex: 'memberType',
      key: 'memberType',
      width: 150,
      align: 'center',
      render: (role) => <Tag color="blue">{role}</Tag>,
    },
    {
      title: '联系方式',
      key: 'contact',
      width: 250,
      align: 'center',
      render: (_, record) => (
        <div>
          {record.phone && <div>
            <PhoneOutlined /> <Text copyable>{record.phone}</Text>
          </div>}
          {record.email && <div style={{ marginTop: 4 }}>
            <MailOutlined /> <Text copyable>{record.email}</Text>
          </div>}
        </div>
      ),
    },
    {
      title: '技能',
      dataIndex: 'skills',
      key: 'skills',
      width: 300,
      align: 'center',
      render: (skills) => {
        // 解析技能数据：现在后端返回JSON字符串格式
        let skillsArray = [];
        if (!skills) {
          return <span style={{ color: '#999' }}>暂无技能</span>;
        }

        if (typeof skills === 'string') {
          try {
            skillsArray = JSON.parse(skills);
          } catch (error) {
            console.error('技能数据解析失败:', error);
            return <span style={{ color: '#999' }}>暂无技能</span>;
          }
        }

        if (!Array.isArray(skillsArray) || skillsArray.length === 0) {
          return <span style={{ color: '#999' }}>暂无技能</span>;
        }

        return (
          <div>
            {skillsArray.map((skill, index) => (
              <Tag key={index} color="blue" style={{ marginBottom: 2 }}>
                {skill}
              </Tag>
            ))}
          </div>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            个人详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            修改资料
          </Button>
          {/* <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button> */}
        </Space>
      ),
    },
  ];

  const handleView = (record) => {
    Modal.info({
      title: `${record.memberName} - ${record.memberType}`,
      width: 700,
      content: (
        <div>
          <Row gutter={[16, 16]}>
            <Col span={8}>
              <Avatar size={80} src={record.avatar} icon={<UserOutlined />} />
            </Col>
            <Col span={16}>
              <Descriptions column={1} size="small">
                <Descriptions.Item label="姓名">{record.memberName}</Descriptions.Item>
                <Descriptions.Item label="角色">{record.memberType}</Descriptions.Item>
                <Descriptions.Item label="电话">{record.phone}</Descriptions.Item>
                <Descriptions.Item label="邮箱">{record.email}</Descriptions.Item>
                <Descriptions.Item label="加入时间">{record.createTime}</Descriptions.Item>
                <Descriptions.Item label="简介">{record.description}</Descriptions.Item>
              </Descriptions>
            </Col>
          </Row>
          <Divider />
          <Row gutter={[16, 16]}>
            <Col span={12}>
              <Card title="账号信息" size="small">
                <p><strong>用户名：</strong> {record.username}</p>
              </Card>
            </Col>
            <Col span={12}>
              <Card title="技能专长" size="small">
                <div>
                  {(() => {
                    // 解析技能数据：现在后端返回JSON字符串格式
                    let skillsArray = [];
                    if (record.skills) {
                      if (typeof record.skills === 'string') {
                        try {
                          skillsArray = JSON.parse(record.skills);
                        } catch (error) {
                          console.error('技能数据解析失败:', error);
                          skillsArray = [];
                        }
                      }
                    }

                    return skillsArray.map(skill => (
                      <Tag key={skill} color="green" style={{ marginBottom: 4 }}>
                        {skill}
                      </Tag>
                    ));
                  })()}
                </div>
              </Card>
            </Col>
          </Row>
        </div>
      ),
    });
  };
  // 编辑成员
  const handleEdit = (record) => {
    setEditingMember(record);
    setIsModalVisible(true);
  };
  // 删除成员
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除成员 "${record.name}" 吗？`,
      onOk() {
        setTableData(tableData.filter(item => item.key !== record.key));
        message.success('删除成功');
      },
    });
  };
  // 添加成员
  const handleAdd = () => {
    setEditingMember(null);
    setIsModalVisible(true);
  };

  // 取消添加/编辑成员
  const handleModalCancel = () => {
    setIsModalVisible(false);
    setEditingMember(null);
  };

  // 添加成员成功
  const handleAddSuccess = async (values) => {
    try {
      setLoading(true);

      // 将用户名同时写入member_code字段
      const memberData = {
        ...values,
        memberCode: values.username
      };

      console.log('发送给后端的数据:', memberData);

      const response = await addMemberApi(memberData);

      if (response && response.code === '0') {
        message.success('新增成员成功');
        // 刷新列表数据
        fetchMembers();
      } else {
        message.error(response.msg || '新增成员失败');
      }
    } catch (error) {
      console.error('新增成员失败:', error);
      message.error('新增成员失败');
    } finally {
      setLoading(false);
    }
  };

  // 编辑成员成功
  const handleEditSuccess = async (values) => {
    try {
      setLoading(true);

      // 编辑时需要包含成员ID
      const memberData = {
        ...values,
        memberCode: values.username,
        id: editingMember.id // 添加成员ID用于更新
      };

      console.log('编辑成员发送给后端的数据:', memberData);

      const response = await updateMemberApi(memberData);

      if (response && response.code === '0') {
        message.success('编辑成员成功');
        // 刷新列表数据
        fetchMembers();
      } else {
        message.error(response.msg || '编辑成员失败');
      }
    } catch (error) {
      console.error('编辑成员失败:', error);
      message.error('编辑成员失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Title level={2}>成员管理</Title>
      {/* 搜索和过滤 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col xs={24} sm={12} md={4}>
            <Card size="small">
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 'bold', color: '#1890ff' }}>
                  {tableData.length}
                </div>
                <div>总成员数</div>
              </div>
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Input
              placeholder="搜索成员姓名"
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<UserOutlined />}
              onPressEnter={handleSearch}
            />
          </Col>
          <Col xs={24} sm={4} md={4}>
            <Select
              placeholder="选择角色"
              style={{ width: '100%' }}
              value={filterRole}
              onChange={setFilterRole}
            >
              <Option value="all">全部角色</Option>
              {memberRoles.map(role => (
                <Option key={role.value} value={role.value}>{role.label}</Option>
              ))}
            </Select>
          </Col>
          <Col xs={24} sm={24} md={6}>
            <Space>
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearch}
              >
                查询
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={handleReset}
              >
                重置
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加成员
              </Button>
              {/* <Button icon={<TeamOutlined />}>
                导出成员表
              </Button> */}
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 成员列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={tableData}
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          onChange={handleTableChange}
        />
      </Card>

      {/* 使用新的AddMembers组件 */}
      <AddMembers
        visible={isModalVisible}
        onCancel={handleModalCancel}
        onSuccess={editingMember ? handleEditSuccess : handleAddSuccess}
        initialValues={editingMember}
        mode={editingMember ? 'edit' : 'add'}
      />
    </div>
  );
};

export default Members;